using MediatR;
using Microsoft.EntityFrameworkCore;
using Medical.Domain;
using Medical.ErrorCode;
using Medical.Infrastructrue.Interfaces;
using Medical.ReadApi.Appcontext.Command;
using Medical.ReadApi.Dto;

namespace Medical.ReadApi.Appcontext.CommandHandler
{
	public class GetDiseasesByDepartmentQueryHandler : IRequestHandler<GetDiseasesByDepartmentQuery, ApiPaging<DiseaseDto>>
	{
		private readonly IBaseRepository<Disease> _repository;

		public GetDiseasesByDepartmentQueryHandler(IBaseRepository<Disease> repository)
		{
			_repository = repository;
		}

		public async Task<ApiPaging<DiseaseDto>> Handle(GetDiseasesByDepartmentQuery request, CancellationToken cancellationToken)
		{
			var query = _repository.GetAll().Where(x => !x.IsDeleted && x.DepartmentId == request.DepartmentId);
			if (!string.IsNullOrEmpty(request.NameKeyword)) query = query.Where(x => x.Name.Contains(request.NameKeyword));

			var totalCount = await query.CountAsync(cancellationToken);
			var items = await query
				.OrderBy(x => x.Name)
				.Skip((request.Page - 1) * request.Size)
				.Take(request.Size)
				.Select(x => new DiseaseDto { DiseaseId = x.DiseaseId, DepartmentId = x.DepartmentId, Name = x.Name, CreatedAt = x.CreatedAt, UpdatedAt = x.UpdatedAt })
				.ToListAsync(cancellationToken);

			var totalPage = (int)Math.Ceiling(totalCount / (double)request.Size);
			return new ApiPaging<DiseaseDto> { totalCount = totalCount, totalPage = totalPage, data = items };
		}
	}
}
